using Catalog.Infrastructure;
using BuildingBlocks;
using Catalog.Application;
using BuildingBlocks.Abstractions.Permissions;
using Catalog.HttpAPI.Permissions;
using Catalog.HttpAPI.Host.Controllers;
using Microsoft.AspNetCore.Authorization;
using PermissionCenter.Grpc;
using Microsoft.AspNetCore.Server.Kestrel.Core;

var builder = WebApplication.CreateBuilder(args);


// 引入统一基础模块服务注册
builder.Services.AddBuildingBlocksCore(builder.Configuration);
builder.Services.AddGrpc(); // 注册 gRPC 服务
/* builder.WebHost.ConfigureKestrel(options =>
{
    options.ListenLocalhost(5210, listenOptions =>
    {
        listenOptions.UseHttps(@"C:\Users\Administrator\Desktop\eShopMicroserviceStarter\localhost.pfx", "123456"); // 使用自签名证书
        listenOptions.Protocols = HttpProtocols.Http2;      // 强制 HTTP/2
    });
});
 */
builder.WebHost.ConfigureKestrel(options =>
{
    options.ListenLocalhost(5013, listenOptions =>
    {
        listenOptions.UseHttps(); // 使用默认开发证书
    });
});


// 注册微服务自身的服务（仓储、业务服务等）
builder.Services.AddCatalogInfrastructure(builder.Configuration);

builder.Services.AddCatalogApplication();


//其他注册
builder.Services.AddOpenApi();

builder.Services.AddControllers();


builder.Services.AddSingleton<IPermissionProvider>(sp =>
    new PermissionScannerProvider(typeof(CatalogItemController).Assembly));

builder.Services.AddSingleton<IAuthorizationHandler, MixedPermissionHandler>();

builder.Services.AddAuthorization(options =>
{
    // 扫描所有控制器上的 [Permission] 特性，动态生成策略
    var permissions = new PermissionScannerProvider(typeof(CatalogItemController).Assembly).GetPermissions();
    foreach (var p in permissions)
    {
        options.AddPolicy(p.resourceId, policy =>
            policy.Requirements.Add(new PermissionRequirement(p.resourceId)));
    }
});

var app = builder.Build();
app.UseCors("DefaultCorsPolicy");


app.UseSwagger();
app.UseSwaggerUI();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}
app.UseRouting();
app.UseAuthentication();          // 如果启用了认证，必须在 Routing 后
app.UseAuthorization();           // 如果启用了授权，必须在 Authentication 后
app.UseHttpsRedirection();
app.MapControllers();

app.Run();

